// pages/integral/orders/orders.ts
import { getIntegralOrderList, takeIntegralOrder, deleteIntegralOrder } from '../../../api/points_mall.js';
import { PAGES, goToPage } from '../../../config/pages.js';

Page({
  data: {
    orderList: [],
    loading: true,
    hasMore: true,
    page: 1,
    status: '',
    statusList: [
      { key: '', name: '全部' },
      { key: '0', name: '待支付' },
      { key: '1', name: '已支付' },
      { key: '2', name: '已发货' },
      { key: '3', name: '已收货' },
      { key: '4', name: '已完成' },
      { key: '-1', name: '已取消' }
    ],
    activeStatus: ''
  },

  onLoad() {
    this.loadOrderList();
  },

  onShow() {
    // 每次显示页面时重新加载订单列表
    this.loadOrderList(true);
  },

  // 加载订单列表
  async loadOrderList(reset = false) {
    if (this.data.loading && !reset) return;
    
    try {
      this.setData({ loading: true });
      const page = reset ? 1 : this.data.page;
      
      const res = await getIntegralOrderList({
        page: page,
        limit: 10,
        status: this.data.status
      });
      
      const newList = reset ? res.data.list : [...this.data.orderList, ...res.data.list];
      this.setData({
        orderList: newList,
        page: page + 1,
        hasMore: res.data.list.length > 0,
        loading: false
      });
    } catch (error) {
      console.error('加载订单列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none',
      });
      this.setData({ loading: false });
    }
  },

  // 筛选订单
  onFilterStatus(e: any) {
    const { status } = e.currentTarget.dataset;
    this.setData({ 
      status: status,
      activeStatus: status,
      orderList: [],
      page: 1
    });
    this.loadOrderList(true);
  },

  // 跳转到订单详情
  goToOrderDetail(e: any) {
    const { orderId } = e.currentTarget.dataset;
    goToPage(PAGES.INTEGRAL_ORDER_DETAIL, { orderId });
  },

  // 确认收货
  async onTakeOrder(e: any) {
    const { orderId } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '确认收货',
      content: '确认已收到商品？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' });
            await takeIntegralOrder({ order_id: orderId });
            
            wx.showToast({
              title: '收货成功',
              icon: 'success',
            });
            
            // 重新加载订单列表
            this.loadOrderList(true);
          } catch (error) {
            console.error('确认收货失败:', error);
            wx.showToast({
              title: error.message || '操作失败',
              icon: 'none',
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  // 删除订单
  async onDeleteOrder(e: any) {
    const { orderId } = e.currentTarget.dataset;
    
    wx.showModal({
      title: '删除订单',
      content: '确定要删除这个订单吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '删除中...' });
            await deleteIntegralOrder({ order_id: orderId });
            
            wx.showToast({
              title: '删除成功',
              icon: 'success',
            });
            
            // 重新加载订单列表
            this.loadOrderList(true);
          } catch (error) {
            console.error('删除订单失败:', error);
            wx.showToast({
              title: error.message || '删除失败',
              icon: 'none',
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  // 查看物流
  goToExpress(e: any) {
    const { orderId } = e.currentTarget.dataset;
    goToPage(PAGES.INTEGRAL_ORDER_EXPRESS, { orderId });
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadOrderList();
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({ orderList: [], page: 1 });
    this.loadOrderList(true).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 获取订单状态文本
  getStatusText(status: number) {
    const statusMap: { [key: number]: string } = {
      0: '待支付',
      1: '已支付',
      2: '已发货',
      3: '已收货',
      4: '已完成',
      '-1': '已取消'
    };
    return statusMap[status] || '未知状态';
  },

  // 获取订单状态样式
  getStatusClass(status: number) {
    const classMap: { [key: number]: string } = {
      0: 'status-pending',
      1: 'status-paid',
      2: 'status-shipped',
      3: 'status-received',
      4: 'status-completed',
      '-1': 'status-cancelled'
    };
    return classMap[status] || 'status-unknown';
  },

  // 跳转到积分商城
  goToIntegralMall() {
    goToPage(PAGES.INTEGRAL_MALL);
  }
});
